<?php
/**
 * @title 62. 不同路径 - 层次遍历
 * @author start2004
 */

// ini_set("memory_limit", "128M");

// class Solution {
//
//     function find() {
//
//     }
// }


class Solution {

    /**
     * @param Integer $m
     * @param Integer $n
     * @return Integer
     */
    function uniquePaths($m, $n) {
        /**
         * @since 2020-12-09 初始化
         */
        $nums = array_fill(0, $n, array_fill(0, $m, 0));
        $nums[0][0] = 1;

        /**
         * @since 2020-12-09 层次遍历
         */
        $nexts = [[0,0]];
        while($nexts){
            $nextTmp = [];

            /**
             * @since 2020-12-09 迭代当前层
             */
            foreach ($nexts as list($w, $h)){
                $count = $nums[$h][$w];

                /**
                 * @since 2020-12-09 向右
                 */
                if($w <= $m-2){
                    $key = ($w+1) ."-". $h;
                    $nextTmp[$key] = [$w+1, $h];
                    $nums[$h][$w+1] += $count;
                } else {}

                /**
                 * @since 2020-12-09 向下
                 */
                if($h <= $n-2){
                    $key = $w ."-". ($h+1);
                    $nextTmp[$key] = [$w, $h+1];
                    $nums[$h+1][$w] += $count;
                } else {}
            }

            /**
             * @since 2020-12-09 下次迭代
             */
            $nexts = $nextTmp;
        }

        /**
         * @return
         */
        return $nums[$n-1][$m-1];
    }
}


/**
 * @url http://127.0.0.1/leetcode/202012/2020.12.09.php
 */
$datas = [
    [3,2], // 3
    [7,3], // 28
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->uniquePaths(...$data);
    // $result = $obj->($xhprof->tree($data));
    // $result = $obj->($xhprof->listNode($data));
    // $result = $obj->find(...$data);
    var_dump($result);
    // if(count($result)<=20){
    //     var_dump($result);
    // } else {
    //     var_dump(count($result));
    // }
    echo str_repeat(PHP_EOL, 3);
    echo str_repeat("<br>", 3);
}

// foreach ($datas as $data){
//     $obj = new $data[0][0](...$data[1][0]);
//
//     for ($i=1; $i<count($data[0]); $i++){
//         $result = $obj->$data[0][$i](...$data[1][$i]);
//
//         echo $data[0][$i] ."(\"". implode(",", $data[1][$i]) ."\") ";
//             if($result === true){
//                 echo "True";
//             } elseif($result === false) {
//                 echo "False";
//             } elseif($result === null) {
//                 echo "Null";
//             } elseif(is_array($result)) {
//                 var_dump($result);
//             } else {
//                 echo $result;
//             }
//         echo PHP_EOL;
//     }
//
//     echo str_repeat(PHP_EOL, 3);
// }
$xhprof->end();
